package com.sunjs.wechat.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunjs.common.kit.HttpClientUtil;
import com.sunjs.wechat.entity.wx.OAuthInfo;
import com.sunjs.wechat.entity.wx.Token;
import com.sunjs.wechat.entity.wx.WeixinUserInfo;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;


/**
 * 	微信共通
     * @ClassName: WeChatCommon
     * @author wang
     * @date 2020年7月14日
     *
 */
public class WeChatCommon {
	private static Logger log = LoggerFactory.getLogger(WeChatCommon.class);

	// 凭证获取（GET）
	public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	

	private static Map<String , Token> tokens = new HashMap<>();
	
	/**
	 * 获取接口访问凭证
	 * 
	 * @param appid 凭证
	 * @param appsecret 密钥
	 * @return
	 */
	public static Token getToken(String appid, String appsecret) {
		Token token = null;
		//判断是否过期
		if(tokens.containsKey(appid + appsecret)){
			token = tokens.get(appid + appsecret);
			if(token.getGetTime() + token.getExpiresIn() - 60 > System.currentTimeMillis()/1000){
				return token;
			}
		}

		token = new Token();
		String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
		// 发起GET请求获取凭证
		JSONObject jsonObject =HttpClientUtil.sendGet(requestUrl);

		if (null != jsonObject) {
			log.info("重新获取token");
			try {
				token.setAccessToken(jsonObject.getString("access_token"));
				token.setExpiresIn(jsonObject.getInt("expires_in"));
				token.setGetTime(System.currentTimeMillis()/1000);
				tokens.put(appid + appsecret, token);
			} catch (JSONException e) {
				token = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return token;
	}

    /**
     * URL编码（utf-8）
     * 
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 根据内容类型判断文件扩展名
     * 
     * @param contentType 内容类型
     * @return
     */
    public static String getFileExt(String contentType) {
        String fileExt = "";
        if ("image/jpeg".equals(contentType))
            fileExt = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileExt = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileExt = ".amr";
        else if ("video/mp4".equals(contentType))
            fileExt = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileExt = ".mp4";
        return fileExt;
    }
    
    /**
     * 获取用户信息
     * 
     * @param accessToken 接口访问凭证
     * @param openId 用户标识
     * @return WeixinUserInfo
     */
    public static WeixinUserInfo getUserInfo(String accessToken, String openId) {
        WeixinUserInfo weixinUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 获取用户信息
        JSONObject jsonObject = HttpClientUtil.sendGet(requestUrl);

        if (null != jsonObject) {
            try {
                weixinUserInfo = new WeixinUserInfo();
                // 用户的标识
                weixinUserInfo.setOpenId(jsonObject.getString("openid"));
                // 关注状态（1是关注，0是未关注），未关注时获取不到其余信息
                weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
                // 用户关注时间
                weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
                // 昵称
                weixinUserInfo.setNickname(jsonObject.getString("nickname"));
                // 用户的性别（1是男性，2是女性，0是未知）
                weixinUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                weixinUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                weixinUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                weixinUserInfo.setCity(jsonObject.getString("city"));
                // 用户的语言，简体中文为zh_CN
                weixinUserInfo.setLanguage(jsonObject.getString("language"));
                // 用户头像
                weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                if(jsonObject.containsKey("unionid")){
                	weixinUserInfo.setUnionid(jsonObject.getString("unionid"));
                }
            } catch (Exception e) {
                if (0 == weixinUserInfo.getSubscribe()) {
                    log.error("用户{}已取消关注", weixinUserInfo.getOpenId());
                } else {
                    int errorCode = jsonObject.getInt("errcode");
                    String errorMsg = jsonObject.getString("errmsg");
                    log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
                }
            }
        }
        return weixinUserInfo;
    }
    
    /**
     * 获取接口访问凭证
     * 
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static JSONObject getOpenId(String appid, String appsecret, String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&grant_type=authorization_code&js_code=JSCODE";
        String requestUrl = url.replace("APPID", appid).replace("APPSECRET", appsecret).replace("JSCODE", code);
        // 发起GET请求获取凭证
        JSONObject jsonObject = HttpClientUtil.sendGet(requestUrl);
        
        return jsonObject;
    }
    
    public static OAuthInfo getOAuthOpenId(String appid, String secret, String code ) {
        OAuthInfo oAuthInfo = null;
        String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String requestUrl = o_auth_openid_url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
        
        JSONObject jsonObject = HttpClientUtil.sendGet(requestUrl);
         
        //oAuthInfo是作者自己把那几个属性参数写在一个类里面了。
        if (null != jsonObject) {
            oAuthInfo = new OAuthInfo();
            oAuthInfo.setOpenid(jsonObject.getString("openid"));
//            oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
//            oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
//            oAuthInfo.setRefreshToken(jsonObject.getString("refresh_token"));
//            oAuthInfo.setScope(jsonObject.getString("scope"));
        }
        return oAuthInfo;
    }
    
    /** 
     * 获取jsapi_ticket
     * 
     * @param appid 凭证 
     * @param appsecret 密钥 
     * @return 
     */ 
    

    /**
     * 获取用户信息网页
     * 
     * @param accessToken 接口访问凭证
     * @param openId 用户标识
     * @return WeixinUserInfo
     */
    public static WeixinUserInfo getUserInfoWangYe(String accessToken, String openId) {
        WeixinUserInfo weixinUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 获取用户信息
        JSONObject jsonObject = HttpClientUtil.sendGet(requestUrl);

        if (null != jsonObject) {
            try {
                weixinUserInfo = new WeixinUserInfo();
                // 用户的标识
                weixinUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                weixinUserInfo.setNickname(jsonObject.getString("nickname"));
               
            } catch (Exception e) {
               log.error("获取用户信息失败 errcode:{} errmsg:{}");
                }
            }
        return weixinUserInfo;
    }
}

